package com.yc.cloud.openai.portal.utils;


import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RemoveWaterTest {

    // 抖音视频解析
    public static Map<String, Object> douyin(String url) {
        // 从URL中提取视频ID
        String id = extractId(url);

        // 检查ID是否有效
        if (id == null || id.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 400);
            error.put("msg", "无法解析视频ID");
            return error;
        }

        // 构造请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1 Edg/122.0.0.0");

        // 发送请求获取视频信息
        String response = curl("https://www.iesdouyin.com/share/video/" + id, headers);
        Pattern pattern = Pattern.compile("window\\._ROUTER_DATA\\s*=\\s*(.*?)\\</script>", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(response);

        if (!matcher.find()) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 201);
            error.put("msg", "解析失败");
            return error;
        }

        try {
            JSONObject videoInfo = new JSONObject(matcher.group(1).trim());
            if (!videoInfo.has("loaderData")) {
                Map<String, Object> error = new HashMap<>();
                error.put("code", 201);
                error.put("msg", "解析失败");
                return error;
            }

            // 替换 "playwm" 为 "play"
            String videoResUrl = videoInfo.getJSONObject("loaderData")
                    .getJSONObject("video_(id)/page")
                    .getJSONObject("videoInfoRes")
                    .getJSONArray("item_list")
                    .getJSONObject(0)
                    .getJSONObject("video")
                    .getJSONObject("play_addr")
                    .getJSONArray("url_list")
                    .getString(0)
                    .replace("playwm", "play");

            // 构造返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("msg", "解析成功");

            Map<String, Object> data = new HashMap<>();
            JSONObject itemInfo = videoInfo.getJSONObject("loaderData")
                    .getJSONObject("video_(id)/page")
                    .getJSONObject("videoInfoRes")
                    .getJSONArray("item_list")
                    .getJSONObject(0);

            data.put("author", itemInfo.getJSONObject("author").getString("nickname"));
            data.put("uid", itemInfo.getJSONObject("author").getString("unique_id"));
            data.put("avatar", itemInfo.getJSONObject("author").getJSONObject("avatar_medium").getJSONArray("url_list").getString(0));
            data.put("like", itemInfo.getJSONObject("statistics").getInt("digg_count"));
            data.put("time", itemInfo.getInt("create_time"));
            data.put("title", itemInfo.getString("desc"));
            data.put("cover", itemInfo.getJSONObject("video").getJSONObject("cover").getJSONArray("url_list").getString(0));
            data.put("url", videoResUrl);

            Map<String, String> music = new HashMap<>();
            music.put("author", itemInfo.getJSONObject("music").getString("author"));
            music.put("avatar", itemInfo.getJSONObject("music").getJSONObject("cover_large").getJSONArray("url_list").getString(0));
            data.put("music", music);

            result.put("data", data);
            return result;

        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("code", 201);
            error.put("msg", "解析失败: " + e.getMessage());
            return error;
        }
    }

    // 辅助方法:从URL中提取视频ID
    private static String extractId(String url) {
        try {
            URL urlObj = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
            conn.setInstanceFollowRedirects(false);
            String location = conn.getHeaderField("Location");

            if (location == null) {
                location = url;
            }

            Pattern pattern = Pattern.compile("[0-9]+");
            Matcher matcher = pattern.matcher(location);

            if (matcher.find()) {
                return matcher.group();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 辅助方法:发送HTTP请求
    private static String curl(String urlString, Map<String, String> headers) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置请求头
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }

            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            return response.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 其他视频平台的解析方法可以按照类似的方式实现
    // ...
    public static void main(String[] args) {
        douyin("8.48 复制打开抖音，看看【叶子宝宝\uD83C\uDF43的作品】听取ma声一片# 吉赛尔进行曲# 卡点舞# 浅跳一... https://v.douyin.com/CeiJhu8WE/ 10/17 LJI:/ E@H.ic");
    }
}
